package com.nsoft.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.nsoft.objects.BookItem;

class BookDownloader extends AsyncTask<Void,Integer,Void>{
	final int DOWNLOAD_DELETEFOLDER_FAILED=-100;
	final int DOWNLOAD_SUCCESSFULLY=150;
	final int DOWNLOAD_EXTRACT_ZIPFILE=151;
	
	private Context context;
	private ProgressDialog progressor=null;
	private BookItem book=null;
	
	public BookDownloader(Context ctx,
				View rowView,BookItem _book){
		this.context=ctx;
		this.progressor=new ProgressDialog(ctx);
		
		this.book=_book;
	}
	
	@Override
	protected void onPreExecute(){
		progressor.setCancelable(false);
		progressor.setMessage(Constant.
				booklist.BLF_FILE_DOWNLOADING);
		progressor.setProgressStyle(
				ProgressDialog.STYLE_HORIZONTAL);
		progressor.setProgress(0);
		progressor.setMax(100);
		progressor.setProgress(0);
		progressor.show();
	}
	
	@Override
	protected Void doInBackground(Void... params){
		InputStream input=null;
		OutputStream output=null;
		/*
		String outPath=utils.getBookPath()+
				'/'+this.book.getContentId();
		*/
		String outPath=utils.getBookPath();
		
		File outPathFile=new File(outPath);
		if (outPathFile.exists()){
			try{
				utils.delete(outPathFile);
			}catch(IOException e){
				Log.v("BookDownloader.deleteFolder()",
					e.getClass()+": "+e.getMessage());
				publishProgress(DOWNLOAD_DELETEFOLDER_FAILED);
				return null;
			}
		}
		outPathFile=new File(outPath);
		outPathFile.mkdir();
		
		try{
			String urlBookPath=book.getDownloadPath();
			URL url=new URL(urlBookPath);
			String fileName=urlBookPath.substring(
					urlBookPath.lastIndexOf("/")+1);
			String outputFilePath=outPath+'/'+fileName;
			
			HttpURLConnection connection=
	        		(HttpURLConnection)url.openConnection();
	        connection.setDoInput(true);
	        connection.connect();
	        input=connection.getInputStream();
	        connection.getContentLength();
	        output=new FileOutputStream(outputFilePath,false);
	        
	        int totalBytesRead=0;
	        int estimateBytes=connection.getContentLength();
	        byte[] buff=new byte[1024];
	        int bytesRead=0;
	        while((bytesRead=input.read(buff))!=-1){
	        	output.write(buff,0,bytesRead);
	        	totalBytesRead+=bytesRead;
	        	publishProgress(
	        		(totalBytesRead*100)/estimateBytes);
	        }
	        output.flush();
	        output.close();
	        
	        publishProgress(DOWNLOAD_EXTRACT_ZIPFILE);
	        utils.unzipFile(outputFilePath,outPath,true);
	        utils.delete(new File(outputFilePath));
	        
	        publishProgress(DOWNLOAD_SUCCESSFULLY);
			return null;
		}catch(IOException e){
			Log.v("BookArrayAdapter.BookDownloader",
		    	e.getClass().toString()+": "+e.getMessage());
		}finally{
			try {
				if (input!=null){
					input.close();
				}
				/*
				if (output!=null){
					output.close();
				}
				*/
			}catch(IOException e){ }
		}
		
		return null;
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		if (values[0]==DOWNLOAD_DELETEFOLDER_FAILED){
			utils.showError(context,
				Constant.DIALOG_ERROR,
				Constant.booklist.
					BLF_ERROR_DELETE_FOLDER_FAILED);
		}else if (values[0]>=0&&values[0]<=100){
			progressor.setProgress(values[0]);
			return;
		}else if (values[0]==DOWNLOAD_SUCCESSFULLY){
			Toast.makeText(context,
					Constant.booklist.BLF_DOWNLOAD_DONE,
					Toast.LENGTH_SHORT).show();
		}else if (values[0]==DOWNLOAD_EXTRACT_ZIPFILE){
			progressor.setMessage(Constant.booklist.
					ELF_DOWNLOAD_EXTRACTING);
			return;
		}
		progressor.dismiss();
	}
	
}
